import sys
from loguru import logger
import os

# 配置日志
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
JSON_LOGS = True if os.getenv("JSON_LOGS", "0") == "1" else False

# 移除默认处理器
logger.remove()

# 添加控制台处理器
logger.add(
    sys.stdout,
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
    level=LOG_LEVEL,
    serialize=JSON_LOGS
)

# 添加文件处理器
logger.add(
    "logs/app.log",
    rotation="500 MB",
    retention="10 days",
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
    level=LOG_LEVEL,
    serialize=JSON_LOGS
)

# 异常处理器
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    
    logger.opt(exception=(exc_type, exc_value, exc_traceback)).error("Uncaught exception:")

sys.excepthook = handle_exception 